package com.kfm.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Map;
import java.util.UUID;

/**
 * RSA工具类
 */
public class RSAUtils {

    public static Map<String, String> getKey() {
        KeyPair rsa = SecureUtil.generateKeyPair("RSA");
        PublicKey aPublic = rsa.getPublic();
        PrivateKey aPrivate = rsa.getPrivate();
        String privateKey = Base64.encode(aPrivate.getEncoded());
        String publicKey = Base64.encode(aPublic.getEncoded());
        return Map.of(Constant.PRIVATE_KEY, privateKey, Constant.PUBLIC_KEY, publicKey);
    }

    /**
     * 按照私钥对于公钥加密的密文解密
     * @param PRIVATE_KEY
     * @param str
     * @return
     */
    public static String decrypt(final String PRIVATE_KEY, String str) {
        RSA rsa = new RSA(PRIVATE_KEY, null);
        byte[] decrypt = rsa.decrypt(str, KeyType.PrivateKey);
        return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
    }


    /**
     * 生成不带 - 的uuid
     * @return
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
